package com.fosun.spr.core.utils;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;

import com.fosun.spr.core.base.SessionModel;
import com.fosun.spr.core.base.model.ISessionSpModel;
import com.fosun.spr.core.cache.LocalCache;
import com.fosun.spr.core.exception.ServiceException;
import com.fosun.spr.core.message.ResultCode;

/**
 * Session管理类
 * 
 * @author chensm@fosun.com Jun 22, 2017
 */
public class SessionUtils {
	private static final int SESSION_SECONDS = 1800;

	public static String set(HttpServletRequest request, String userId, String teamId) {
		SessionModel sessionModel = new SessionModel();
		sessionModel.setUserId(userId);
		sessionModel.setTeamId(teamId);

		String token = UUID.randomUUID() + "-" + System.currentTimeMillis();

		// request.getSession().setAttribute("sessionModel", sessionModel);
		LocalCache cache = LocalCache.getInstance();
		cache.set("SESSION_TOEKN_" + token, sessionModel);

		return token;
	}

	// public static SessionModel get(HttpServletRequest request){
	// //return (SessionModel)request.getSession().getAttribute("sessionModel");
	// String session_debug = request.getHeader("session_debug$mq");
	// String session_debug2 = request.getParameter("session_debug$mq");
	// if("1".equals(session_debug)||"1".equals(session_debug2)){
	// SessionModel model = new SessionModel();
	// model.setUserId("1");
	// model.setTeamId("1");
	// return model;
	// }
	//
	// String token = request.getHeader("session_token");
	// LocalCache cache = LocalCache.getInstance();
	// return (SessionModel)cache.get("SESSION_TOEKN_"+token);
	// }
	/**
	 * Shiro的登录支持
	 * 
	 * @param request
	 * @param spModel
	 */
	public static void fillSpModel(HttpServletRequest request, ISessionSpModel spModel) {
		// SessionModel sessionModel = get(request);
		SessionModel token = (SessionModel) SecurityUtils.getSubject().getPrincipal();
		// For debug
		// token = new SessionModel();token.setTeamId("1");token.setUserId("1");
		if (token == null) {
			throw new ServiceException(ResultCode.NEEDLOGIN_ERROR);
		}
		spModel.setSessionUserId(token.getUserId());
		spModel.setSessionTeamId(token.getTeamId());
	}

}
